import { useState, useEffect } from 'react';
import { ConfigProvider, App as AntdApp } from 'antd';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import './App.css';

// 布局组件
import MainLayout from './components/layout/MainLayout';

// 页面组件
import Login from './pages/login';
import Register from './pages/register';
import Welcome from './pages/welcome';
import UserProfile from './pages/user';
import Settings from './pages/setting';
import UserGroupPage from './pages/userGroup';
import GroupMembersPage from './pages/userGroup/members';

// 认证组件和服务
import PrivateRoute from './components/auth/PrivateRoute';
import authApi from './api/auth';

// 已登录用户禁止访问的路由（如登录页）
const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  if (authApi.isAuthenticated()) {
    // 已登录，重定向到欢迎页
    return <Navigate to="/welcome" replace />;
  }

  return <>{children}</>;
};

function App() {
  const [themeColor, setThemeColor] = useState('#1890ff');

  // 从本地存储中获取主题颜色
  useEffect(() => {
    const storedColor = localStorage.getItem('themeColor');
    if (storedColor) {
      setThemeColor(storedColor);
    }
  }, []);

  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: themeColor,
        },
      }}
    >
      <AntdApp>
        <BrowserRouter>
          <Routes>
            {/* 公共路由 */}
            <Route
              path="/login"
              element={
                <PublicRoute>
                  <Login />
                </PublicRoute>
              }
            />
            <Route
              path="/register"
              element={
                <PublicRoute>
                  <Register />
                </PublicRoute>
              }
            />

            {/* 需要认证的路由 */}
            <Route
              path="/"
              element={
                <PrivateRoute>
                  <MainLayout />
                </PrivateRoute>
              }
            >
              <Route index element={<Navigate to="/welcome" replace />} />
              <Route path="welcome" element={<Welcome />} />
              <Route path="user" element={<UserProfile />} />
              <Route path="setting" element={<Settings />} />
              <Route path="user-groups" element={<UserGroupPage />} />
              <Route path="user-groups/:groupId/members" element={<GroupMembersPage />} />
              {/* 可以添加更多路由 */}
            </Route>

            {/* 默认路由 - 重定向到欢迎页面 */}
            <Route path="*" element={<Navigate to="/welcome" replace />} />
          </Routes>
        </BrowserRouter>
      </AntdApp>
    </ConfigProvider>
  );
}

export default App;
